package com.cz.nongyetongv5.activity;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.adapter.dao.DatabaseHelper;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.badgeview.BadgeView;
import com.cz.nongyetongv5.custom.dialog.CustomDialog;
import com.cz.nongyetongv5.custom.wheelview.Utils;
import com.cz.nongyetongv5.task.SynchronizedDataService;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.ImageUtil;
import com.cz.nongyetongv5.utils.UpdateDataUtil;
import com.ronri.ams.bean.loginbean;

import java.io.File;
import java.io.FilenameFilter;
import java.util.List;

public class MainActivity extends SyncActivity {

	public static boolean ISFROMGUIDE = false;

	public boolean reinitok = false;

	// 定义FragmentTabHost对象
	private FragmentTabHost mTabHost;

	// 定义一个布局
	private LayoutInflater layoutInflater;

	// 定义数组来存放Fragment界面
	private Class fragmentArray[] = { ShouYeActivity.class,
			YongHuActivity.class, GengDuoActivity.class, GuanYuActivity.class };

	// 定义数组来存放按钮图片
	private int mImageViewArray[] = { R.drawable.shouye_icon,
			R.drawable.yonghu_icon, R.drawable.btn_more_icon,
			R.drawable.guanyu_icon };
	// Tab选项卡的文字
	private String mTextviewArray[] = { "首页", "用户", "更多", "关于" };

	private User user = null;

	/**
	 * 消息接收者
	 */
	private MessageReceiver mMessageReceiver;

	public void registerMessageReceiver() {
		mMessageReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(MainActivity.class.getName());
		registerReceiver(mMessageReceiver, filter);
	}

	// 重新初始化数据
	private void reinitData() {

		SharedPreferences sharedData = MainActivity.this.getSharedPreferences(
				CommonConstants.SHARED_REFERENCES_REINITDATA,
				Context.MODE_PRIVATE);

		boolean isDo = sharedData.getBoolean("isdoreinit", false);

		// 如果数据库版本>= 8 并且 没有初始化过 并且不是从引导页来的
		if (CommonConstants.DATABASE_VERSION >= 7 && isDo == false
				&& ISFROMGUIDE == false) {

			final CustomDialog messageDialog = new CustomDialog(
					MainActivity.this);

			messageDialog.setMessage("软件需要整理数据,整理过程可能持续1~2分钟,请您务必保持网络畅通..");

			messageDialog.setOnActionClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					if (!CommonConstants.isNetworkConnected(MainActivity.this)) {

						Toast.makeText(
								MainActivity.this,
								getResources().getString(
										R.string.error_no_network),
								Toast.LENGTH_SHORT).show();

						return;
					} else {

						messageDialog.dismiss();

						AsyncTask<Integer, Integer, Integer> moveData = new AsyncTask<Integer, Integer, Integer>() {

							@Override
							protected Integer doInBackground(Integer... params) {

								int result = 0;

								try {

									DatabaseHelper db = new DatabaseHelper(
											MainActivity.this,
											CommonConstants.DBNAME, null,
											CommonConstants.DATABASE_VERSION);

									db.delete("TOWN");
									db.delete("BEIJIANDANWEI");
									db.delete("JIANCHADANWEI");
									db.delete("JIANGUANRENYUAN");
									db.delete("LINKMAN");
									db.delete("CHOUYANJIGOU");
									db.delete("DUCHAXUNCHA");

									UpdateDataUtil dataUtilSyn = new UpdateDataUtil(
											db, MainActivity.this, null);

									dataUtilSyn.add("TOWN");

									final String TAG = "synservice";

									Log.d(TAG, "Town同步完成...");

									dataUtilSyn.add("BEIJIANDANWEI");

									dataUtilSyn.update("BEIJIANDANWEI");

									dataUtilSyn.delete("BEIJIANDANWEI");

									Log.d(TAG, "被检单位同步完成...");

									dataUtilSyn.add("JIANCHADANWEI");
									dataUtilSyn.update("JIANCHADANWEI");
									dataUtilSyn.delete("JIANCHADANWEI");
									Log.d(TAG, "检测单位同步完成...");

									dataUtilSyn.add("JIANGUANRENYUAN");
									dataUtilSyn.update("JIANGUANRENYUAN");
									dataUtilSyn.delete("JIANGUANRENYUAN");
									Log.d(TAG, "监管人员同步完成...");

									dataUtilSyn.add("LINKMAN");
									dataUtilSyn.update("LINKMAN");
									dataUtilSyn.delete("LINKMAN");
									Log.d(TAG, "联系人同步完成...");

									dataUtilSyn.add("CHOUYANJIGOU");
									dataUtilSyn.update("CHOUYANJIGOU");
									dataUtilSyn.delete("CHOUYANJIGOU");
									Log.d(TAG, "抽验机构同步完成...");
									dataUtilSyn.add("DUCHAXUNCHA");
									Log.d(TAG, "同步完成!!");

									MainActivity.ISFROMGUIDE = true;

								} catch (Exception e) {

									e.printStackTrace();

									result = -1;
								}

								return result;
							}

							private CustomDialog customDialog = null;

							protected void onPreExecute() {

								customDialog = new CustomDialog(
										MainActivity.this);

								customDialog.setMessage("正在整理数据..");

								customDialog.showWait();

							};

							@Override
							protected void onPostExecute(Integer result) {

								if (customDialog != null) {
									customDialog.dismiss();
								}

								SharedPreferences sharedData = MainActivity.this
										.getSharedPreferences(
												CommonConstants.SHARED_REFERENCES_REINITDATA,
												Context.MODE_PRIVATE);

								Editor editable = sharedData.edit();

								// 存储已经重新初始化完毕
								editable.putBoolean("isdoreinit", true);

								editable.commit();

								// 让后台同步执行
								reinitok = true;

								// 启动后台同步
								onStart();

							}

						};

						moveData.execute();

					}

				}
			});

			messageDialog.setActionTxt(getResources().getString(
					R.string.jiandujiancha_btn_sureitem));

			messageDialog.show();

		} else {
			reinitok = true;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().add(0, this);

		// 重新初始化数据
		reinitData();

		initView();

		user = (User) getIntent().getSerializableExtra("user");

		// 注册消息接受者
		registerMessageReceiver();

		checkUpdate();

		// /**
		// * 判断服务是否启动
		// */
		// boolean isRunning = false;
		//
		// ActivityManager activityManager = (ActivityManager) MainActivity.this
		// .getSystemService(Context.ACTIVITY_SERVICE);
		//
		// List<ActivityManager.RunningServiceInfo> serviceList =
		// activityManager
		// .getRunningServices(30);
		//
		// for (int i = 0; i < serviceList.size(); i++) {
		// if (serviceList.get(i).service.getClassName().equals(
		// FloatWindowService.class.getName())) {
		// isRunning = true;
		// break;
		// }
		// }
		//
		// if (!isRunning) {
		//
		// Intent intent = new Intent(MainActivity.this,
		// com.cz.nongyetongv5.floatview.FloatWindowService.class);
		// startService(intent);
		// }

		if (CommonConstants.isNetworkConnected(this)) {
			ionCreate(savedInstanceState);
		}

		SharedPreferences sharedPreferences = this
				.getSharedPreferences(
						CommonConstants.SHARED_REFERENCES_TAG,
						Context.MODE_PRIVATE);

		if(sharedPreferences.getBoolean("autologin",false)){
			String szString=sharedPreferences.getString("loginInfo","");
			loginbean login = JSON.parseObject(szString, loginbean.class);
			InitApplication.LoginInfo=login;
		}

	}

	/**
	 * 初始化组件
	 */
	private void initView() {
		// 实例化布局对象
		layoutInflater = LayoutInflater.from(this);

		// 实例化TabHost对象，得到TabHost
		mTabHost = (FragmentTabHost) findViewById(R.id.tabhost);

		mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

		// 得到fragment的个数
		int count = fragmentArray.length;

		for (int i = 0; i < count; i++) {
			// 为每一个Tab按钮设置图标、文字和内容
			TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i])
					.setIndicator(getTabItemView(i));
			// 将Tab按钮添加进Tab选项卡中
			mTabHost.addTab(tabSpec, fragmentArray[i], null);

		}

		/**
		 * 进行是否有新版本的检测
		 */
		ViewGroup group = (ViewGroup) mTabHost.getTabWidget()
				.getChildTabViewAt(2);

		BadgeView badgeView = null;

		if (group.getTag() instanceof BadgeView) {

			badgeView = (BadgeView) group.getTag();

		} else {

			badgeView = new BadgeView(this, group.getChildAt(0));

			int topVal = Utils.dip2px(this, 2);

			badgeView.setBadgeMargin(
					badgeView.getLeft() + badgeView.getWidth(),
					badgeView.getTop() + topVal);

			badgeView.setText("1");

			badgeView.setBadgeBackgroundColor(Color.RED);

			badgeView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);

		}

		InitApplication application = (InitApplication) getApplicationContext();

		if (application.hasNewVersion()) {

			badgeView.show();

		} else {

			badgeView.hide();
		}

	}

	/**
	 * 给Tab按钮设置图标和文字
	 */
	public View getTabItemView(int index) {

		View view = layoutInflater.inflate(R.layout.tab_item_view, null);

		ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
		imageView.setImageResource(mImageViewArray[index]);

		TextView textView = (TextView) view.findViewById(R.id.textview);
		textView.setText(mTextviewArray[index]);

		return view;
	}

	// 当点击退出的时候
	@Override
	public void onBackPressed() {

		final CustomDialog exitDialog = new CustomDialog(MainActivity.this);

		exitDialog.setOnCancleClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				exitDialog.dismiss();
			}
		});

		exitDialog.setOnActionClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				InitApplication initApplication = (InitApplication) getApplicationContext();

				initApplication.getActivities().remove(MainActivity.this);

				// Intent intent = new Intent(MainActivity.this,
				// com.cz.nongyetongv5.floatview.FloatWindowService.class);
				//
				// stopService(intent);

				MainActivity.this.finish();

				System.exit(0);
			}
		});

		exitDialog.setMessage(getResources().getString(R.string.exit_message));

		exitDialog.setCancleTxt(getResources().getString(
				R.string.jiandujiancha_item_cancle));

		exitDialog.setActionTxt(getResources().getString(
				R.string.jiandujiancha_item_sure));

		exitDialog.show();

	}

	@Override
	protected void onDestroy() {

		// 取消消息接受者注册
		unregisterReceiver(mMessageReceiver);

		super.onDestroy();
	}

	/**
	 * 消息的接受者
	 */
	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (MainActivity.class.getName().equals(intent.getAction())) {

				int currentTabPosition = mTabHost.getCurrentTab();

				Fragment fragment = getSupportFragmentManager().getFragments()
						.get(currentTabPosition);

				if (fragment != null && fragment instanceof ShouYeActivity) {

					ShouYeActivity shouYeActivity = (ShouYeActivity) fragment;

					shouYeActivity.refreshNewsCount();

				}

			}
		}
	}

	/**
	 * 检测更新
	 */

	@SuppressLint("NewApi")
	private void checkUpdate() {

		InitApplication application = (InitApplication) getApplicationContext();

		if (application.hasNewVersion()) {

			final CustomDialog updateDialog = new CustomDialog(this);

			updateDialog.setHeightPercent(0.6F);

			View view = getLayoutInflater()
					.inflate(R.layout.start_update, null);

			TextView tvUpdateLog = (TextView) view
					.findViewById(R.id.tvUpdateLog);

			tvUpdateLog.setText(application.getUpdateLog());

			updateDialog.setView(view);

			updateDialog.setTitle("程序更新(更新版本\u0020:\u0020"
					+ application.getMaxVersion().getVersion() + ")");

			updateDialog.setOnActionClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					updateDialog.dismiss();

					Toast.makeText(MainActivity.this, "正在为您后台更新..您可以继续工作..",
							Toast.LENGTH_LONG).show();

					String apkUrl = getString(R.string.new_version_url);

					apkUrl = apkUrl.replaceAll("region_code", new ConfigUtil(
							getResources()).getRegionCode());

					final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

					DownloadManager.Request request = new DownloadManager.Request(
							Uri.parse(apkUrl));

					request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
							| DownloadManager.Request.NETWORK_WIFI);

					request.setTitle("更新");
					request.setDescription("正在为您下载更新..");
					//
					request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

					request.setMimeType("application/cn.trinea.download.file");

					final File file = ImageUtil.getThisAppDataFile();

					File[] childs = file.listFiles(new FilenameFilter() {

						@Override
						public boolean accept(File dir, String filename) {

							if (filename.startsWith("newapp")) {

								return true;
							}

							return false;
						}
					});

					/**
					 * 进行文件的清理
					 */
					for (File child : childs) {
						child.delete();
					}

					final File apkFile = new File(file, "newapp.apk");

					request.setDestinationUri(Uri.fromFile(apkFile));

					request.setVisibleInDownloadsUi(true);

					final long downloadId = downloadManager.enqueue(request);

					IntentFilter filter = new IntentFilter(
							DownloadManager.ACTION_DOWNLOAD_COMPLETE);

					BroadcastReceiver receiver = new BroadcastReceiver() {
						@Override
						public void onReceive(Context context, Intent intent) {
							long reference = intent.getLongExtra(
									DownloadManager.EXTRA_DOWNLOAD_ID, -1);

							if (downloadId == reference) {

								if (apkFile.exists()) {

									installApk(apkFile);

								}
							}
						}
					};
					getApplicationContext().registerReceiver(receiver, filter);

					IntentFilter clickItemFilter = new IntentFilter(
							DownloadManager.ACTION_NOTIFICATION_CLICKED);

					BroadcastReceiver clickItemReceiver = new BroadcastReceiver() {
						@Override
						public void onReceive(Context context, Intent intent) {
							String extraID = DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS;
							long[] references = intent
									.getLongArrayExtra(extraID);
							for (long reference : references)
								if (reference == downloadId) {

									Toast.makeText(getApplicationContext(),
											"下载更新完成后会自动打开...",
											Toast.LENGTH_SHORT).show();

								}
						}
					};

					getApplicationContext().registerReceiver(clickItemReceiver,
							clickItemFilter);

				}

			});

			if (!application.getMaxVersion().isMust()) {

				updateDialog.setOnCancleClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						updateDialog.dismiss();
					}
				});
				updateDialog.setCancleTxt("稍后再说");

			}

			updateDialog.setActionTxt("立即更新");

			updateDialog.show();

		}
	}

	private void installApk(File file) {
		Intent intent = new Intent();
		intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		startActivity(intent);

		this.finish();
	}

	@Override
	protected void onStart() {

		if (reinitok) {
			boolean isRunning = false;

			ActivityManager activityManager =

					(ActivityManager) MainActivity.this
							.getSystemService(ACTIVITY_SERVICE);

			List<ActivityManager.RunningServiceInfo> serviceList

					= activityManager.getRunningServices(Integer.MAX_VALUE);

			for (int i = 0; i < serviceList.size(); i++) {

				if (serviceList.get(i).service.getClassName().equals(
						SynchronizedDataService.class.getName()) == true) {
					isRunning = true;
					break;

				}

			}

			if (isRunning) {

				// Log.d(CommonConstants.LOG_TAG, "同步服务已经启动.. 正在后台同步数据...");
			} else {
				// Log.d(CommonConstants.LOG_TAG, "同步服务尚未启动.. 正在开启同步服务...");

				Intent intent = new Intent(MainActivity.this,
						SynchronizedDataService.class);

				intent.putExtra("user", user);

				startService(intent);

			}
		}
		super.onRestart();
	}

}
